//
//  PhotosViewController.m
//  NoneCar
//
//  Created by DongSen on 2018/7/11.
//  Copyright © 2018年 董森森. All rights reserved.
//

#import "HUPhotoBrowser.h"
#import "CoreLocationManager.h"
#import "UIImage+WaterMark.h"
#import "WatermarkView.h"
#import "ShowImageView.h"
#import "PhotoCollectionViewCell.h"
#import "PhotosViewController.h"
@interface PhotosViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic)  NSMutableArray * dataArray;
@property (weak, nonatomic) IBOutlet WatermarkView *waterView;

@end

@implementation PhotosViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"拍照";
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerNib:[UINib nibWithNibName:@"PhotoCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"PhotoCollectionViewCell"];
    [self.collectionView reloadData];
    [self.waterView setUpUI];
    self.waterView.alpha = 0;
    self.waterView.nameLabel.text = @"姓名:董森森";
    self.waterView.numberLabel.text = @"E/N:";
    self.waterView.timeLabel.text = @"times";
    self.waterView.locationLabel.text = @"位置";
    WeakSelf(self);

    if([CoreLocationManager determineWhetherTheAPPOpensTheLocation]){
        [[CoreLocationManager shareLocationManager] startLocation];
        [[CoreLocationManager shareLocationManager] getLocationInfo:^(NSString *proviceStr, NSString *cityStr, NSString *distr, NSString *others) {
            weakSelf.waterView.locationLabel.text = [NSString stringWithFormat:@"%@%@%@%@",proviceStr,cityStr,distr,others];
        }];
    }
    else{
        UIAlertController *alt = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请输入您的位置信息" preferredStyle:UIAlertControllerStyleAlert];
        [alt addTextFieldWithConfigurationHandler:^(UITextField *textField){

            textField.placeholder = @"请输入详情信息";
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertTextFieldDidChange:) name:UITextFieldTextDidChangeNotification object:textField];
            


        }];
//        UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
            UITextField *inputInfo = alt.textFields.firstObject;
            weakSelf.waterView.locationLabel.text = inputInfo.text;
            //这边可添加网络请求的代码。
        }];
//        [alt addAction:cancelAction];
        okAction.enabled = NO;//此处确定按钮在输入框内没有内容时置灰不可用
        

        [alt addAction:okAction];
        [self presentViewController:alt animated:YES completion:^{
            
        }];
        
    }

    // Do any additional setup after loading the view from its nib.
}

- (void)alertTextFieldDidChange:(NSNotification *)notification{
    
    UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
    if (alertController) {
        
        UITextField *wordNameTextField = alertController.textFields.firstObject;
        UIAlertAction *okAction = alertController.actions.lastObject;
        okAction.enabled = ![@"" isEqualToString:wordNameTextField.text];//输入框有内容时可用
    }
}
-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count+1;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    PhotoCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PhotoCollectionViewCell" forIndexPath:indexPath];;
    if (indexPath.row) {
        cell.photosImageView.image = [UIImage imageWithData:self.dataArray[indexPath.row-1]];
    }
    else{
        cell.photosImageView.image = nil;
    }
   return  cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(kSCREEN_W/5-1, kSCREEN_W/5-1);
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 1;
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 1;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==0) {
        WeakSelf(self);
        UIImagePickerController* ipc                = [[UIImagePickerController alloc] init];
        ipc.delegate                                = weakSelf;
        ipc.sourceType                              = UIImagePickerControllerSourceTypeCamera;
        ipc.cameraDevice                            = UIImagePickerControllerCameraDeviceRear;
        ipc.videoQuality = UIImagePickerControllerQualityTypeLow;
        ipc.showsCameraControls                     = YES;
//        ipc.allowsEditing = YES;
        [weakSelf presentViewController:ipc animated:YES completion:^{
        }];
    }
    else{
        PhotoCollectionViewCell * cell =(PhotoCollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
        [HUPhotoBrowser showFromImageView:cell.photosImageView withImages:self.dataArray atIndex:indexPath.row-1];
    }
}
// 获取图片后的操作
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage * image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        //获取图片的metadata数据信息
    if (image.size.height>1000||image.size.width>1000){
        CGSize newSize;
        if (image.size.height>1000) {
            newSize = CGSizeMake(1000, 1000/(image.size.width/image.size.height));
        }
        else{
            newSize = CGSizeMake(1000/(image.size.height/image.size.width),1000);
        }
        image = [image compressImagewithSize:newSize];
        }
    image = [image compressImage];
    image = [image imageWithWaterMask:self.waterView.screenImage];
    
//    NSString * path_document = NSHomeDirectory();
    //设置一个图片的存储路径
//    NSString * timestr =[NSString stringWithFormat:@"%f",[NSDate date].timeIntervalSince1970];
//    timestr= [timestr stringByReplacingOccurrencesOfString:@"." withString:@""];
//    NSString * strName = [NSString stringWithFormat:@"/Documents/%@.png",timestr];
//    NSString * imagePath = [path_document stringByAppendingString:strName];
    //把图片直接保存到指定的路径（同时应该把图片的路径imagePath存起来，下次就可以直接用来取）
    NSData * data = UIImagePNGRepresentation(image);
//    [data writeToFile:imagePath atomically:YES];
    [self.dataArray addObject:data];
//    NSLog(@"%@",self.dataArray);
    [self.collectionView reloadData];
    [picker dismissViewControllerAnimated:YES completion:nil];
    // 设置图片
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
